import React, { useEffect, useState } from 'react';

import { getProvince, getCity } from '../../http/api';
import './index.less';
import { Cascader } from 'antd';
// interface itemarr {
//   value: string;
//   label: string;
//   isLeaf: boolean;
// }
interface PropsType {
  defaultValue: any[];
  setCheckCity: any;
}
export const CityCascader: React.FC<PropsType> = (props) => {
  const { defaultValue } = props;
  const optionLists = [
    {
      value: '2',
      label: '北京',
      isLeaf: false,
    },
  ];
  const [options, setOptions] = useState(optionLists);
  useEffect(() => {
    getProvince({}).then((res: any) => {
      let provinceArray = [];
      for (let i in res.data) {
        provinceArray.push({
          value: i,
          label: res.data[i],
          isLeaf: false,
        });
      }
      setOptions(provinceArray);
    });
  }, []);

  const onChange = (value: any, selectedOptions: any) => {
    let cityid = '';
    let cityname = '';
    if (selectedOptions.length === 4) {
      selectedOptions.forEach((element: any) => {
        cityid = cityid + ',' + element.value;
        cityname = cityname + ',' + element.label;
      });
      console.log(cityid.substr(1) + '-' + cityname.substr(1));
      props.setCheckCity(cityid.substr(1) + '-' + cityname.substr(1));
    }
  };

  const loadData = (selectedOptions: any) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    getCity({
      province_id: targetOption.value,
    }).then((res: any) => {
      let cityArray = [];
      targetOption.loading = false;
      let isLeaf = false;
      if (selectedOptions.length >= 3) {
        isLeaf = true;
      }
      for (let i in res.data) {
        cityArray.push({
          value: i,
          label: res.data[i],
          isLeaf: isLeaf,
        });
      }
      targetOption.children = cityArray;
      setOptions([...options]);
    });
  };

  return (
    <div>
      <Cascader
        style={{ width: '300px' }}
        defaultValue={defaultValue}
        options={options}
        loadData={loadData}
        onChange={onChange}
        changeOnSelect
        placeholder='请选择城市'
      />
    </div>
  );
};
